package com.koron.css2.systemManage.servlet;

import com.koron.css2.ApplicationConfig;
import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.systemManage.bean.OrgUserBean;
import com.koron.css2.systemManage.bean.RoleBean;
import com.koron.css2.systemManage.mapper.OrgUserMapper;
import com.koron.css2.systemManage.service.IRoleService;
import com.koron.css2.systemManage.service.ServiceFactory;
import com.koron.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.Arrays;
import java.util.List;
/**
 * 设置为管理员
 * @author 59532
 *
 */
public class SetupAdmin implements ServerInterface{

	private static Logger log = LogManager.getLogger(SetupAdmin.class);

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		MessageBean<Void> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "设置成功", Void.class);
		try {
			String account = JsonUtils.objectToPojo(req.getData(), String.class);
			if(StringUtils.isEmpty(account)) {
				msg.setCode(Constant.MESSAGE_INT_FAIL);
				msg.setDescription("账号不能为空");
				return msg;
			}
			IRoleService service = ServiceFactory.getRoleService();
			List<RoleBean> roles = service.listRole(ApplicationConfig.getAppCustomerAppid());
			for(RoleBean role : roles) {
				if("管理员".equals(role.getRoleName())) {
					OrgUserMapper orgUserMapper = factory.getMapper(OrgUserMapper.class);
					OrgUserBean orgUser = orgUserMapper.selectByAccount(userInfo.getUserInfo().getAcount());
					service.addRoleUser(role.getRoleCode(), Arrays.asList(orgUser));
					log.info("账号：{}设置为管理员成功", account);
				}
			}
		}catch(Exception ex) {
			log.error("设置管理员出错");
			msg.setCode(Constant.MESSAGE_INT_FAIL);
			msg.setDescription("设置管理员出错");
		}
		return msg;
	}
}
